public class KAResourceAllcation
{
     public String KASelectedValue{get;set;}
     public Activity_Information__c ActivityInit{get;set;}
     public CommonAttribute PlaceAttribute{get;set;}
     public List<ActivityCompetitionBrandEntry> CompetitionBrandList{get;set;}//竞品信息
     public Boolean IsSelectedAllCompetition{get;set;}//竟品费用全选
     public string CompetitorOtletName{get;set;}
     public List<Activity_Competition_Brand_Detail__c> CompetitionBrandDetailList{get;set;}
     public List<String> ETColumnList{get;set;}
     public Set<String> OutletColumnList{get;set;}
     public Integer Rows{get;set;}
    public  List<DynamicColumnEntry> DynamicColumnEntryList{get;set;}
    public Boolean WhetherDisplaySubmitOrSaveButtonOrNot{get;set;}//按钮是否可用
    public List<CityResourceAllcation__c> resourceDetailList;
    public CommonMethod getCommonMethod;
   // public List<SelectOption> ParticipatorKAList{get;set;}//参与列表中的KA
     public List<SelectOption> KAList{get;set;}
     public List<string>userKAList{get;set;}
     Transient  public Blob GetFileValue{get;set;}//导入进来的文件
     public decimal TotalMoney{get;set;}
     public String SSYPromotionTypeSelectedValue{get;set;}
     public String SSYKACostTypeSelectedValue{get;set;}
     public String CostSourceSelectedValue{get;set;} 
    //加载ET资源
      public List<AllocationResourceEntry> ResourceEntryList
     {
         get
         {
             String filter=' and KAName__c=\''+KASelectedValue+'\' and Type__c=\'KACity\'';
               
               return getCommonMethod.LoadResourceAllcationListByCity(filter,RecordId);
         }
     }
    public String RecordId
   {
       get
       {
           return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
       }
       set;
   }
    //获取当前KA参与列表
      public List<ParticipatorArea__c> getParticipatorAreaList
      {
          get
          {
              return [select id,KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c=:KASelectedValue];
          }
      }
      
    public KAResourceAllcation(ApexPages.StandardController controller)
     {
        InitReLoadAllData();
     }
     //设置KA状态，控制按钮是否可见
     public void SetKAStatus()
     {
         if(ActivityInit.Activity_Stage__c=='活动已取消')
         {
             WhetherDisplaySubmitOrSaveButtonOrNot=false;
         }
         else
         {
             Date StartDT=ActivityInit.Activity_Start_Date__c;                   
             if(Date.today()>= StartDT.addDays(-21))//开始活动前21天不可以调时间
            {  
                WhetherDisplaySubmitOrSaveButtonOrNot=false;
             }
             else
             {
                 if(getParticipatorAreaList!=NULL && getParticipatorAreaList.size()>0)
                 {
                       if(getParticipatorAreaList[0].KA_Status__c == '已审批' || getParticipatorAreaList[0].KA_Status__c=='KAM已提交')          
                          WhetherDisplaySubmitOrSaveButtonOrNot=false;
                       else
                           WhetherDisplaySubmitOrSaveButtonOrNot=true; 
                  }
                  else
                  {
                      WhetherDisplaySubmitOrSaveButtonOrNot=false;
                  }
             }
          }
     }
     public void LoadCompetitionData()
     {
           //加载竞品
         if(CompetitionBrandList==NULL)
                 CompetitionBrandList=new List<ActivityCompetitionBrandEntry>();
          else
              CompetitionBrandList.clear();
            for(Activity_Competition_Brand_Information__c acb:[Select  Name, Activity_Information__c, Type__c, Competition_Cost_Source__c, Competition_Cost_Type__c,
                                                 Competition_Promotion_Type__c FROM Activity_Competition_Brand_Information__c 
                                                 where Activity_Information__c=:RecordId and Type__c='KA' and   KA__c=:KASelectedValue])
            {
                CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,acb));
            }
     }
     public void  InitReLoadAllData()//初始化数据
     {
          //userKAList=new List<string>();
         getCommonMethod=new CommonMethod();
         
         if(KAList==NULL)
             KAList=new List<SelectOption>();
         else
             KAList.clear();
       KAList=getCommonMethod.UserKAOptionList();
       
        if(KASelectedValue==NULL)
            KASelectedValue=KAList[0].getValue();
             
         
          resourceDetailList=new List<CityResourceAllcation__c>();
          
          //ParticipatorKAList=getCommonMethod.ParticipatorKAList(RecordId,false);
          
         WhetherDisplaySubmitOrSaveButtonOrNot=true;
         PlaceAttribute=new CommonAttribute();
         ActivityInit=[Select Id,Name,  Activity_End_Date__c, Activity_Notice__c, Activity_Stage__c, Activity_Start_Date__c, 
                             Activity_Type_State__c, Activity_Type__c,Serial_Number__c FROM Activity_Information__c where id=: RecordId];
                             
        
             SetKAStatus();    
             LoadCompetitionData();
            LoadOutletList();
            TotalMoney=TotalMoneyByKA();
     }
          //按KA汇总金额
     public decimal TotalMoneyByKA()
     {
         List<AggregateResult>TotalNumberList=[select sum(Money__c) totalNumber from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId and Participator_Detail_Outlet__r.KA__c=:KASelectedValue];
         if(TotalNumberList[0].get('totalNumber')!=NULL)
             return decimal.valueOf((Double)TotalNumberList[0].get('totalNumber'));
         else
             return 0;
     }
     
     public PageReference LoadNewOutlet()
     {
        // getCommonMethod.GenerateNewOutlet(RecordId,1);//加载新增的门店
        // GenerateCompetition();//生成竞品
         return null;
     }
     public void LoadOutletList()
     {
      
            String filter=' and KAName__c=\''+KASelectedValue+'\' and Type__c=\'KACity\' ';
            resourceDetailList=getCommonMethod.LoadCityList(filter,RecordId);//加载门店列表
            ETColumnList=getCommonMethod.GetDynamicETColumnList(resourceDetailList);//获取列名
           // System.assert(false,resourceDetailList);
           DynamicColumnEntryList=getCommonMethod.GetDynamicEntryList(resourceDetailList);//获取门店列表
      //   QueryCompetitionList();//加载竞品
     }
     
      //添加竞品信息
     public PageReference addCompetitionBrandAction()
     {
         if(CompetitionBrandList==NULL)
             CompetitionBrandList=new  List<ActivityCompetitionBrandEntry>();
             try
             {
                  if(CompetitionBrandList.size()>=5)
                     throw new CustomException ('竞品信息不能超过5种');
                 if(PlaceAttribute.SSYPromotionTypeSelectedValue=='' || PlaceAttribute.SSYPromotionTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竟品促销形式');
                 if(PlaceAttribute.SSYKACostTypeSelectedValue=='' || PlaceAttribute.SSYKACostTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用形式');
                  if(PlaceAttribute.CostSourceSelectedValue=='' || PlaceAttribute.CostSourceSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用来源');
                      
                    //如果添加重复的竞品信息则返回空  
                   for(ActivityCompetitionBrandEntry entry:CompetitionBrandList)   
                   {
                       if(entry.ActivityCompetitionMsg.Competition_Cost_Source__c==PlaceAttribute.CostSourceSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Cost_Type__c== PlaceAttribute.SSYKACostTypeSelectedValue&&
                          entry.ActivityCompetitionMsg.Competition_Promotion_Type__c==PlaceAttribute.SSYPromotionTypeSelectedValue)
                              return null;
                   }
                    Activity_Competition_Brand_Information__c activity=new Activity_Competition_Brand_Information__c(Activity_Information__c=RecordId,
                                                                                                  Competition_Cost_Source__c=PlaceAttribute.CostSourceSelectedValue,
                                                                                                  Competition_Cost_Type__c=PlaceAttribute.SSYKACostTypeSelectedValue,
                                                                                                   Competition_Promotion_Type__c=PlaceAttribute.SSYPromotionTypeSelectedValue,
                                                                                                    Type__c='KA',KA__c=KASelectedValue );
                                                                                     
                   CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,activity));
                   
                   insert activity;
                  
                   //查找参与列表明细outlet
                   List<Activity_Competition_Brand_Detail__c> competitionDetail=new List<Activity_Competition_Brand_Detail__c>(); 
                 for(Participator_Detail_Outlet__c par: [select id,OwnerId from Participator_Detail_Outlet__c where ActivityId__c=:RecordId and KA__c=:KASelectedValue ])
                 {
                      Activity_Competition_Brand_Detail__c acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=activity.id,
                                                                                                     Participator_Detail_Outlet__c=par.Id,OwnerId=par.OwnerId);
                      
                     competitionDetail.add(acbd);
                 }
                 insert competitionDetail;
             }
             catch(Exception ex)
            {
                  ApexPages.addMessages(ex);
                 return null;
            }
             PlaceAttribute.SSYPromotionTypeSelectedValue='';
             PlaceAttribute.SSYKACostTypeSelectedValue='';
             PlaceAttribute.CostSourceSelectedValue='';
             return null;
     }
      public PageReference DeleteCompetitionBrandAction()
      {
         for(Integer i=0;i<CompetitionBrandList.size();i++)
         {
              ActivityCompetitionBrandEntry entry=CompetitionBrandList[i];
             if(entry.IsCheck)
             {
                 CompetitionBrandList.remove(i);
                  delete [select id from Activity_Competition_Brand_Detail__c where Activity_Competition_Brand_Information__c=:entry.ActivityCompetitionMsg.Id];
                 delete [select id from Activity_Competition_Brand_Information__c where id=:entry.ActivityCompetitionMsg.Id];
                 i--;
             }
         }
         TotalMoneyByKA();
          return null;
      }
      public PageReference QueryCompetition()
      {
          QueryCompetitionList();
          return null;
      }
      public void QueryCompetitionList()
      {
           String filter='';
          if(PlaceAttribute.RegionSelectedValue != NULL && PlaceAttribute.RegionSelectedValue != '0')
              filter+=' and OutletRegion__c=\''+PlaceAttribute.RegionSelectedValue+'\'';
          if(PlaceAttribute.SubRegionSelectedValue!=NULL && PlaceAttribute.SubRegionSelectedValue!='0')
          {
              filter+=' and  OutletSubregion__c=\''+PlaceAttribute.SubRegionSelectedValue+'\'';
          }
          if(PlaceAttribute.AreaSelectedValue!=NULL && PlaceAttribute.AreaSelectedValue!='0')
          {
              filter+=' and OutletArea__c=\''+PlaceAttribute.AreaSelectedValue+'\'';
          }
          if(PlaceAttribute.CitySelectedValue!=NULL && PlaceAttribute.CitySelectedValue!='0')
          {
              filter+=' and OutletCity__c=\''+PlaceAttribute.CitySelectedValue+'\'';
          }
          if(CompetitorOtletName!=NULL && CompetitorOtletName!='' )
          {
              filter+=' and OutletName__c=\''+CompetitorOtletName+'\'';
          }
           if(PlaceAttribute.OutletTypeSelectedValue!=NULL && PlaceAttribute.OutletTypeSelectedValue!='')
          {
             
              filter+=' and OutletType__c=\''+PlaceAttribute.OutletTypeSelectedValue+'\'';
          }
           if(PlaceAttribute.ChannelSelectedValue!=NULL && PlaceAttribute.ChannelSelectedValue!='')
          {
              filter+=' and OutletChannel__c=\''+PlaceAttribute.ChannelSelectedValue+'\'';
          }
          //添加的竞品条件
            if(SSYPromotionTypeSelectedValue!=NULL && SSYPromotionTypeSelectedValue!='')
          {
              filter+=' and Promotion_Type__c=\''+SSYPromotionTypeSelectedValue+'\'';
          }
             if(SSYKACostTypeSelectedValue!=NULL && SSYKACostTypeSelectedValue!='')
          {
              filter+=' and Cost_Type__c=\''+SSYKACostTypeSelectedValue+'\'';
          }
             if(CostSourceSelectedValue!=NULL && CostSourceSelectedValue!='')
          {
              filter+=' and Competition_Cost_Source__c=\''+CostSourceSelectedValue+'\'';
          }
          
          string sql='select id,OutletName__c,Display_Type__c ,Competition_Cost_Source__c,Cost_Type__c,Promotion_Type__c,'+
                          ' Money__c,End_Date__c,Start_Date__c,Participator_Detail_Outlet__r.Outlet_Name__r.OutletCode__c from  Activity_Competition_Brand_Detail__c'+
                          '  where Activity_Competition_Brand_Information__r.Type__c=\'KA\' and  ActivityId__c=\''+RecordId+'\' and Participator_Detail_Outlet__r.KA__c=\''+KASelectedValue+'\'';  
          if(filter!='')
              sql+=filter;
        //      throw new CustomException (sql);
         CompetitionBrandDetailList=Database.query(sql);
      }
      public PageReference QueryOutletList()//按门店查询
      {
          LoadOutletList();//加载资源分配信息
          SetKAStatus();//设置KA状态
          LoadCompetitionData();//加载竞品信息
          TotalMoney=TotalMoneyByKA();//显示总金额
          //点击确定后显示处理竞信的开始时间和结束时间
          QueryCompetitionList();
         
          return null;
      }
      public PageReference SaveActivity()
      {
        //验证，设置竞品投入资料中，若金额不为空且费用申请方不是合同内费用，则必须填入开始时间和结束时间
         try{
          for(Activity_Competition_Brand_Detail__c abd:CompetitionBrandDetailList){
            if((abd.Money__c!=null || abd.Start_Date__c!=null || abd.End_Date__c!=null) && abd.Competition_Cost_Source__c!='合同内费用'){ 
                if(abd.Promotion_Type__c=='陈列租金'){
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null || abd.Display_Type__c==null)
                       throw new CustomException ('设置了金额，则开始时间和结束时间不能为空,并且是陈列租金形式的必须选择陈列形式！');
                }else{
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null)
                      throw new CustomException ('设置了金额，则开始时间和结束时间不能为空！');
                }
             }else{
                if((abd.Start_Date__c!=null && abd.End_Date__c==null) || (abd.Start_Date__c==null && abd.End_Date__c!=null))
                      throw new CustomException ('开始时间和结束时间不能只填写一个，请认真填写开始时间和结束时间！');
             }   
               if(abd.Start_Date__c!=null && abd.End_Date__c!=null){
                 if(abd.Start_Date__c>abd.End_Date__c)
                   throw new CustomException ('开始时间不能大于结束时间！');
            } 
           }
           
             SaveData();
             InitReLoadAllData();
          }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
      
         
         return null;   
      }
      public PageReference SubmitActivity()
      {
         //验证，设置竞品投入资料中，若金额不为空且费用申请方不是合同内费用，则必须填入开始时间和结束时间
         try{
          for(Activity_Competition_Brand_Detail__c abd:CompetitionBrandDetailList){
          if((abd.Money__c!=null || abd.Start_Date__c!=null || abd.End_Date__c!=null) && abd.Competition_Cost_Source__c!='合同内费用'){ 
                if(abd.Promotion_Type__c=='陈列租金'){
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null || abd.Display_Type__c==null)
                       throw new CustomException ('设置了金额，则开始时间和结束时间不能为空,并且是陈列租金形式的必须选择陈列形式！');
                }else{
                    if(abd.Money__c==null || abd.Start_Date__c==null || abd.End_Date__c==null)
                      throw new CustomException ('设置了金额，则开始时间和结束时间不能为空！');
                }
             }else{
                if((abd.Start_Date__c!=null && abd.End_Date__c==null) || (abd.Start_Date__c==null && abd.End_Date__c!=null))
                      throw new CustomException ('开始时间和结束时间不能只填写一个，请认真填写开始时间和结束时间！');
             }   
               if(abd.Start_Date__c!=null && abd.End_Date__c!=null){
                 if(abd.Start_Date__c>abd.End_Date__c)
                   throw new CustomException ('开始时间不能大于结束时间！');
            } 
            
           }
          }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
        
          List<ParticipatorArea__c> updateParList=new List<ParticipatorArea__c>();
         for(ParticipatorArea__c par: [select id,KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c=:KASelectedValue])
         {
             par.KA_Status__c='KAM已提交'; 
             updateParList.add(par);
         } 
         update updateParList;//更新KA提交状态
         try
         {
              SaveData();
         }
         catch(Exception ex)
         {
             ApexPages.addMessages(ex);
             return null;
         }
          WhetherDisplaySubmitOrSaveButtonOrNot=false;
        //发送邮件到总部
        //获取用户信息
        User u=getCommonMethod.getUserInfo();
      
         String BodyString=u.Name+'已调整了【'+ActivityInit.Name+'】活动,请登陆凤凰系统进行确认,谢谢！';
          String subject='确认【'+ActivityInit.Name+'】活动的KA资源调整';
          EmailHander.SendMail(BodyString,getCommonMethod.getUserEmailAddress('NTMKT',RecordId),subject,'',null);
          //  System.assert(false,getCommonMethod.getUserEmailAddress('NTMKT',RecordId));
     //   pageReference pr = new pageReference('/'+RecordId);     
      //    pr.setredirect(true);   
     //   return pr;
         return null;
      }
      public void SaveData()
      {
         Activity_Information__c ActivityStatus=[select IsCompleted__c from Activity_Information__c where id=:RecordId];
         if(ActivityStatus.IsCompleted__c)
         {
             //先删除
             delete [select id from CityResourceAllcation__c where Type__c='KACity' and Activity_Information__c=:RecordId and KAName__c=:KASelectedValue];
             //重新保存城市分配量
             getCommonMethod.SaveCityResourceAllocation('KA',RecordId,KASelectedValue,NULL,ActivityInit.Activity_Type__c,DynamicColumnEntryList);
             //分配给相应的门店
             
             // getCommonMethod.SaveAdjustmentResourceForOulet(DynamicColumnEntryList,resourceDetailList,null);//保存ＫＡ
            // update ActivityInit;//更新活动
             if(CompetitionBrandDetailList!=null)
                 update CompetitionBrandDetailList;//更新竞品
         }
         else
         {
             throw new CustomException('后台正在处理数据，请稍后再保存或提交');
         }
      }
      public PageReference  FillCompetitionList()
      {
          for(Activity_Competition_Brand_Detail__c acbd:CompetitionBrandDetailList)
          {
              acbd.Start_Date__c=ActivityInit.Activity_Start_Date__c;
              acbd.End_Date__c=ActivityInit.Activity_End_Date__c;
          }
          return null;
      }
     public PageReference RedirectUploadFilePage()
     {
      //   if(WhetherDisplaySubmitOrSaveButtonOrNot)
      //   {
             PageReference pf=new PageReference('/apex/KAUploadResourceFile?id='+RecordId);
             pf.setRedirect(true);
             return pf;
      //   }
         return null;
     }
      //生成所有的OT竞品费用信息，由于总部发起活动时要处理的数据量比较大，所以放到此处处理
  /*     public void GenerateCompetition()
     {
         List<Activity_Competition_Brand_Detail__c> cometitionList=new  List<Activity_Competition_Brand_Detail__c>();
         
        Integer countNumber=[select Count() from Activity_Competition_Brand_Detail__c 
                                                    where ActivityId__c=:RecordId and Activity_Competition_Brand_Information__r.Type__c='OT'];
        if(countNumber==0)
        {
            List<Participator_Detail_Outlet__c> parDetailList=[select id,OwnerId from Participator_Detail_Outlet__c
                                                                                          where  ActivityId__c=:RecordId and OutletResourceType__c='OT'];
                                                                                               
             for(Activity_Competition_Brand_Information__c activity:[select id from Activity_Competition_Brand_Information__c
                                                                                                    where Activity_Information__c=:RecordId and Type__c='OT'])
             {
                  for(Participator_Detail_Outlet__c par:parDetailList)
                  {
                      cometitionList.add(new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=activity.Id,
                                                                                                                     Participator_Detail_Outlet__c=par.Id,
                                                                                                                     OwnerId=par.OwnerId));
                  }
             }    
             insert  cometitionList;                                                                   
        }
     }*/
  
      
     /*
      public pageReference UploadFileAction()//上传文件
      {
          map<id,Activity_Competition_Brand_Detail__c> CompetitionList=new map<id,Activity_Competition_Brand_Detail__c>([select id,End_Date__c,Money__c, Start_Date__c,Display_Type__c
                                                                                                           from Activity_Competition_Brand_Detail__c
                                                                                                           where ActivityId__c=:RecordId]);
          map<id,Resource_Allocation_Detail__c> resourceDetailList=new map<id,Resource_Allocation_Detail__c>([select id,Resource_Number__c,ProductId__c,ProductName__c 
                                                                                                                                                                            from Resource_Allocation_Detail__c
                                                                                                                                                                            where ActivityId__c=:RecordId]);
          string[] contentList=GetFileValue.toString().split('\n');
          for(Integer i=1;i<contentList.size();i++)
          {
              string[] rowString=contentList[i].split(',');
              if(rowString[4]!=NULL)//ET1
              {
                 Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[4]);
                 rad.Resource_Number__c=Integer.valueOf(rowString[6]);
                 resourceDetailList.put(rad.id,rad);
                
              }
              if(rowString[7]!=NULL)//ET2
              {
                  Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[7]);
                 rad.Resource_Number__c=Integer.valueOf(rowString[9]);
                 resourceDetailList.put(rad.Id,rad);
              }
               if(rowString[10]!=NULL && rowString[10]!='')//ET3
              {
                  Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[10]);
                 rad.Resource_Number__c=Integer.valueOf(rowString[12]);
                 resourceDetailList.put(rad.id,rad);
              }
               if(rowString[13]!=NULL && rowString[13]!='')//ET4
              {
                  Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[13]);
                 rad.Resource_Number__c=Integer.valueOf(rowString[15]);
                 resourceDetailList.put(rad.id,rad);
              }
               if(rowString[16]!=NULL && rowString[16]!='')//ET5
              {
                  Resource_Allocation_Detail__c rad=(Resource_Allocation_Detail__c)resourceDetailList.get(rowString[16]);
                 rad.Resource_Number__c=Integer.valueOf(rowString[18]);
                 resourceDetailList.put(rad.id,rad);
              }
              if(rowString[34]!=NULL && rowString[34]!='')//Competition 1
              {
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[34]);
                  acbd.Start_Date__c=Date.valueOf(rowString[38]);
                  acbd.End_Date__c=Date.valueOf(rowString[39]);
                  acbd.Money__c=Decimal.valueOf(rowString[40]);
                  acbd.Display_Type__c=rowString[41];
                  CompetitionList.put(acbd.id,acbd);
              }
               if(rowString[42]!=NULL && rowString[42]!='')//Competition 2
              {
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[42]);
                  acbd.Start_Date__c=Date.valueOf(rowString[46]);
                  acbd.End_Date__c=Date.valueOf(rowString[47]);
                  acbd.Money__c=Decimal.valueOf(rowString[48]);
                  acbd.Display_Type__c=rowString[49];
                  CompetitionList.put(acbd.id,acbd);
              }
                if(rowString[50]!=NULL && rowString[50]!='')//Competition 3
              {
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[50]);
                  acbd.Start_Date__c=Date.valueOf(rowString[54]);
                  acbd.End_Date__c=Date.valueOf(rowString[55]);
                  acbd.Money__c=Decimal.valueOf(rowString[56]);
                  acbd.Display_Type__c=rowString[57];
                  CompetitionList.put(acbd.id,acbd);
              }
                if(rowString[58]!=NULL && rowString[58]!='')//Competition 4
              {
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[58]);
                  acbd.Start_Date__c=Date.valueOf(rowString[62]);
                  acbd.End_Date__c=Date.valueOf(rowString[63]);
                  acbd.Money__c=Decimal.valueOf(rowString[64]);
                  acbd.Display_Type__c=rowString[65];
                  CompetitionList.put(acbd.id,acbd);
              }
              if(rowString[66]!=NULL && rowString[66]!='')//Competition 5
              {
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[66]);
                  acbd.Start_Date__c=Date.valueOf(rowString[70]);
                  acbd.End_Date__c=Date.valueOf(rowString[71]);
                  acbd.Money__c=Decimal.valueOf(rowString[72]);
                  acbd.Display_Type__c=rowString[73];
                  CompetitionList.put(acbd.id,acbd);
              }
          }
         update resourceDetailList.values();
          return null;
      }
      */
 
    
    
         public pageReference UploadFileAction()//上传竞品文件
      {
        
   
   /*      Set<String> kaList=new Set<String>();
         User u=[select Key_Account__c from User where id=:UserInfo.getUserId()];
         string kaString=u.Key_Account__c;
            for(string str:kaString.split(';'))
            {
                kaList.add(str);
            }*/
          map<id,Activity_Competition_Brand_Detail__c> CompetitionList=new map<id,Activity_Competition_Brand_Detail__c>([select id,End_Date__c,Money__c, Start_Date__c,Display_Type__c
                                                                                                           from Activity_Competition_Brand_Detail__c
                                                                                                           where ActivityId__c=:RecordId 
                                                                                                          // and Activity_Competition_Brand_Information__r.KA__C=:kaList
                                                                                                           ]);      

       //上传文件前实际资源总数，根据KA，类型，产品名称来区分
     
         string[] contentList=GetFileValue.toString().split('\n');
       
         if(ActivityInit.Activity_Type__c=='SSY')
            //getCommonMethod.getFileContent(CompetitionList,resourceDetailList,contentList,'SSY',keySet,AllPretotNumList);
            getCopetitionFileContent(CompetitionList,contentList);
         else if(ActivityInit.Activity_Type__c=='KA')
            getCopetitionFileContent(CompetitionList,contentList);
         return null;
      }
      //上传CityResourceAllocation文件
           public pageReference UploadCityAllocationFileAction()
      {
     //先删除ResourceAllocation
         Set<String> kaList=new Set<String>();
         User u=[select Key_Account__c from User where id=:UserInfo.getUserId()];
         string kaString=u.Key_Account__c;
            for(string str:kaString.split(';'))
            {
                kaList.add(str);
            }
          delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:RecordId and Participator_Detail_Outlet__r.KA__c=:kaList];
          List<Resource_Allocation_Detail__c> radList=new List<Resource_Allocation_Detail__c>();
          
          map<id,CityResourceAllcation__c> CityresourceDetailList=new map<id,CityResourceAllcation__c>([select id,ResourceNumber__c,CityName__c,KAName__c,PackSize__c,Resource_Allocation__c,Type__c,Resource_Allocation__r.Product_Name__r.Name
                                                                                                                                                                            from CityResourceAllcation__c
                                                                                                                                                                            where Activity_Information__c=:RecordId
                                                                                                                                                                          //  and Participator_Detail_Outlet__r.KA__C=:kaList
                                                                                                                                                                            ]);
       
         List<Activity_Target_And_Allocation_Total__c> cityTargetList=new List<Activity_Target_And_Allocation_Total__c>();
         List<Participator_Detail_Outlet__c> ParOutletList=new List<Participator_Detail_Outlet__c>();
         //查询KA门店,和KA城市的Target
         ParOutletList=[select Id,TargetNumber__c,KA__c,City__c,OutletResourceType__c 
                                   from Participator_Detail_Outlet__c 
                                    where Participator_Area__r.Activity_Name__c=:RecordId];
          cityTargetList=[select CityName__c,TargetNumber__c,KAName__c,Type__c from Activity_Target_And_Allocation_Total__c
                                      where Activity_Information__c=:RecordId];
        
   //   System.assert(false,ParOutletList);
         //按城市保存参与者
         map<string,List<Participator_Detail_Outlet__c>> mapParticipatorList=new map<string,List<Participator_Detail_Outlet__c>>();
         for(Participator_Detail_Outlet__c pdo: ParOutletList)
         {
             if(!mapParticipatorList.containsKey(pdo.KA__c+pdo.City__c+pdo.OutletResourceType__c))
             {
                 List<Participator_Detail_Outlet__c> parList=new List<Participator_Detail_Outlet__c>();
                 parList.add(pdo);
                 mapParticipatorList.put(pdo.KA__c+pdo.City__c+pdo.OutletResourceType__c,parList);
             }
             else
             {
                 List<Participator_Detail_Outlet__c> parList=mapParticipatorList.get(pdo.KA__c+pdo.City__c+pdo.OutletResourceType__c);
                 parList.add(pdo);
                 mapParticipatorList.put(pdo.KA__c+pdo.City__c+pdo.OutletResourceType__c,parList);
             }
         }
         //取出城市Target
         map<string,double> mapCityTargetList=new map<string,double>();
         for(Activity_Target_And_Allocation_Total__c ataat:cityTargetList)
         {
             mapCityTargetList.put(ataat.KAName__c+ataat.CityName__c+ataat.Type__c,ataat.TargetNumber__c);
         }
      
      
       //上传文件前实际资源总数，根据KA，类型，产品名称来区分
        Set<String> keySet=new Set<String>();
        map<String,Integer> AllPretotNumList=new map<String,Integer>();
        for(CityResourceAllcation__c cra:CityresourceDetailList.values()){
              String key=cra.KAName__c+cra.Type__c+cra.Resource_Allocation__r.Product_Name__r.Name;  //标识
              keySet.add(key);
              integer num=Integer.valueOf(cra.ResourceNumber__c);
              if(AllPretotNumList.containsKey(key))             
                  num=AllPretotNumList.get(key)+num;
               AllPretotNumList.put(key,num);
            
        }      
         
       
         string[] contentList=GetFileValue.toString().split('\n');
       
         if(ActivityInit.Activity_Type__c=='SSY')
          //  getCommonMethod.getFileContent(CompetitionList,resourceDetailList,contentList,'SSY',keySet,AllPretotNumList);
             getCityAllocationFileContent(mapCityTargetList,mapParticipatorList,CityresourceDetailList,contentList,'SSY',keySet,AllPretotNumList);
         else if(ActivityInit.Activity_Type__c=='KA')
          // getFileContent(CompetitionList,resourceDetailList,contentList,'KA',keySet,AllPretotNumList);
          getCityAllocationFileContent(mapCityTargetList,mapParticipatorList,CityresourceDetailList,contentList,'KA',keySet,AllPretotNumList);
         return null;
      }
      
      //赋值并获取分配数值
    public map<String,Integer> getResourceAllDetailByFile(List<Resource_Allocation_Detail__c> craList,map<String,double> targetMap,map<String,List<Participator_Detail_Outlet__c>> paMap,map<id,CityResourceAllcation__c> CityresourceDetailList,string[] rowString,integer i,map<String,Integer> totNumMap,String key){
           if(rowString[i]!=NULL && rowString[i]!='') {
            Integer num=0;
            CityResourceAllcation__c cra=(CityResourceAllcation__c)CityresourceDetailList.get(rowString[i]);
             if(rowString[i+2]!=null && rowString[i+2]!=''){
                if(Integer.valueOf(rowString[i+2])<0)
                      throw new CustomException ('资源分配数值不能小于0');
                num=Integer.valueOf(rowString[i+2]);
             }
                 // System.assert(false,cra);
                 cra.ResourceNumber__c=num;
                 CityresourceDetailList.put(cra.id,cra);
                 String keyStr=cra.KAName__c+cra.CityName__c+cra.Type__c;   //标识CityName__c
             //    String flag=cra.KAName__c+cra.Resource_Allocation__c+cra.Type__c;
                 if(totNumMap.containsKey(key))             
                     num=totNumMap.get(key)+num;
                 totNumMap.put(key,num);
                 List<Participator_Detail_Outlet__c> pdoList=new List<Participator_Detail_Outlet__c>();
                 pdoList=paMap.get(keyStr);
                 double target=targetMap.get(keyStr);
                 List<Resource_Allocation_Detail__c> resultList=getCommonMethod.CreateResourceAllocationDetail(pdoList,cra.Resource_Allocation__c,target,num*cra.PackSize__c.intValue());

                 craList.addAll(resultList);
              }
                 return totNumMap;
    }
    public void getActivityBrandDetailByFile(map<id,Activity_Competition_Brand_Detail__c> CompetitionList,string[] rowString,integer i){
            if(rowString[i]!=NULL && rowString[i]!='')//Competition 1
              {
                 if(Decimal.valueOf(rowString[i+6])<0)
                      throw new CustomException ('金额分配数值不能小于0');
                  Activity_Competition_Brand_Detail__c acbd=CompetitionList.get(rowString[i]);
                  if(rowString[i+4]!=NULL && rowString[i+4]!='')
                       acbd.Start_Date__c=Date.valueOf(rowString[i+4]);
                  if(rowString[i+5]!=NULL && rowString[i+5]!='')
                      acbd.End_Date__c=Date.valueOf(rowString[i+5]);
                  if(rowString[i+6]!=NULL && rowString[i+6]!='')
                      acbd.Money__c=Decimal.valueOf(rowString[i+6]);
                  if(rowString[i+7]!=NULL && rowString[i+7]!='')
                      acbd.Display_Type__c=rowString[i+7];
                  CompetitionList.put(acbd.id,acbd);
              }
    }
     //获取上传文件内容并赋值，针对SSY和Region活动
    public void getCityAllocationFileContent(map<String,double> targetMap,map<String,List<Participator_Detail_Outlet__c>> paMap,map<id,CityResourceAllcation__c> CityresourceDetailList,string[] contentList,String typeStr,Set<String> keySet,map<String,Integer> AllPretotNumList){
         map<String,Integer> totNummap=new map<String,Integer>(); //ET1分配总数
         List<Resource_Allocation_Detail__c> radList=new List<Resource_Allocation_Detail__c>();
    

           for(integer i=1;i<contentList.size();i++){
              string[] rowString=contentList[i].split(',');
            //  string[] rowString=b64Decrypted.split(',');
              String ETkey1=rowString[1]+rowString[3]+rowString[5];   //标识
           
              String ETkey2=rowString[1]+rowString[3]+rowString[8];   //标识
              String ETkey3=rowString[1]+rowString[3]+rowString[11];   //标识
              String ETkey4=rowString[1]+rowString[3]+rowString[14];   //标识
              String ETkey5=rowString[1]+rowString[3]+rowString[17];   //标识  
            
              getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,4,totNummap,ETkey1);   
              getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,7,totNummap,ETkey2);
              getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,10,totNummap,ETkey3);
              getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,13,totNummap,ETkey4);
              getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,16,totNummap,ETkey5);
         
              if(typeStr=='KA'){
                String FGkey1=rowString[1]+rowString[3]+rowString[20];   //标识
                String FGkey2=rowString[1]+rowString[3]+rowString[23];   //标识
                String FGkey3=rowString[1]+rowString[3]+rowString[26];   //标识
                String FGkey4=rowString[1]+rowString[3]+rowString[29];   //标识
                String FGkey5=rowString[1]+rowString[3]+rowString[32];   //标识
                
                getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,19,totNummap,FGkey1);
                getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,22,totNummap,FGkey2);
                getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,25,totNummap,FGkey3);
                getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,28,totNummap,FGkey4);
                getResourceAllDetailByFile(radList,targetMap,paMap,CityresourceDetailList,rowString,31,totNummap,FGkey5);
        
                }
          }
          //判断用户分配总数与数据库中总数是否一致，不一致则不能上传文件  
        
         for(String key:keySet){
          
             if(totNummap.containsKey(key)) {
            //System.assert(false,keySet);
                if(totNummap.get(key)!=AllPretotNumList.get(key))
                     throw new CustomException ('分配总数与实际存在总数不相等，请重新分配');
             }
         }
         update CityresourceDetailList.values();
         insert radList;
    }
    
       //获取上传竞品文件内容并赋值，针对SSY和KA活动
    public void getCopetitionFileContent(map<id,Activity_Competition_Brand_Detail__c> CompetitionList,string[] contentList){
       //  map<String,Integer> totNummap=new map<String,Integer>(); //ET1分配总数

           for(integer i=1;i<contentList.size();i++){
              string[] rowString=contentList[i].split(',');
        
              getActivityBrandDetailByFile(CompetitionList,rowString,4);  //Competition 1
              getActivityBrandDetailByFile(CompetitionList,rowString,12);  //Competition 2
              getActivityBrandDetailByFile(CompetitionList,rowString,20);  //Competition 3
              getActivityBrandDetailByFile(CompetitionList,rowString,28);  //Competition 4
              getActivityBrandDetailByFile(CompetitionList,rowString,36);  //Competition 5
              getActivityBrandDetailByFile(CompetitionList,rowString,44);  //Competition 6
              getActivityBrandDetailByFile(CompetitionList,rowString,52);  //Competition 7
              getActivityBrandDetailByFile(CompetitionList,rowString,60);  //Competition 8
            
          }
         update CompetitionList.values();
    }
}